package com.bijava.utils;

import org.springframework.util.ReflectionUtils;

import java.beans.Introspector;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;

/**
 * @author bishichu
 * @version 1.0
 * @since 20-11-19
 */
public class FieldUtils {
    private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");
    private static final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");

    private FieldUtils(){
        throw new IllegalStateException("FieldUtils class");
    }

    public static <T> String getEntityField(Function<T, Object> func){
        return fnToFieldName(func);
    }

    private static <T> String fnToFieldName(Function<T, Object> func) {
        try {
            Method method = func.getClass().getDeclaredMethod("writeReplace");
            ReflectionUtils.makeAccessible(method);
            SerializedLambda serializedLambda = (SerializedLambda)method.invoke(func);
            String getter = serializedLambda.getImplMethodName();
            if (GET_PATTERN.matcher(getter).matches()) {
                getter = getter.substring(3);
            } else if (IS_PATTERN.matcher(getter).matches()) {
                getter = getter.substring(2);
            }

            return Introspector.decapitalize(getter);
        } catch (Exception var4) {
            throw new RuntimeException(var4);
        }
    }

    public static Map<String, Object> transUnderlineMap(Map<String, Object> entityMap) {
        Map<String, Object> paramsMap = new HashMap<>();
        entityMap.forEach((key, value) -> {
            if (value != null) {
                String underlineKey = CoreUtils.camelToUnderline(key);
                paramsMap.put(underlineKey, value);
            }
        });

        return paramsMap;
    }
}
